﻿package Cain.pcxbook 
{
	import Cain.pcxbook.PcxAutoSize;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	/**
	 * 圖像陣列 v1.01
	 * 主要用途為可以循序載入圖形,並且可以目前需要的圖像隨時讀取圖形
	 * 全部載完發出 "COMPLETE" 事件
	 * @author Cain
	 */
	public class PcxList extends EventDispatcher
	{
		private var pcx_url_arr:Vector.<String>;
		private var now_load_id:int = 0;
		private var mynum:int;
		private var pcx_arr:Vector.<PcxAutoSize>;
		private var ww:Number;
		private var hh:Number;
		private var full:Boolean;
		private var loadingmc:String;
		/**
		 * 建構
		 * @param	_arr 圖形路徑字串的陣列
		 */
		public function PcxList(_arr:Array)
		{
			pcx_url_arr = new Vector.<String>();
			pcx_arr = new Vector.<PcxAutoSize>();
			for each (var _url:String in _arr) 
			{
				mynum = pcx_url_arr.push(_url);
				var _pcx:PcxAutoSize = new PcxAutoSize();
				pcx_arr.push(_pcx);
			}
		}
		/**
		 * 總數
		 */
		public function get num():int 
		{
			return mynum;
		}
		/**
		 * 設定規格
		 * @param	_ww 寬
		 * @param	_hh 高
		 * @param	_full 是否滿版
		 * @param	_loadingmc 載入動畫
		 */
		public function setup(_ww:Number,_hh:Number,_full:Boolean=true,_loadingmc:String = null):void 
		{
			ww = _ww;
			hh = _hh;
			full = _full;
			loadingmc = _loadingmc;
		}
		/**
		 * 載入
		 * @param	_id 序號
		 */
		public function load(_id:int = 0):void 
		{
			loadpcx(_id);
		}
		private function loadpcx(_now:int):void
		{
			var _pcx:PcxAutoSize;
			var ok:Boolean = pcx_arr[_now].isload;
			if (!ok) 
			{
				_pcx = pcx_arr[_now];
				_pcx.setup(ww, hh);
				var _url:String = pcx_url_arr[_now];
				_pcx.addEventListener(Event.COMPLETE, onCOMPLETE);
				if (loadingmc==null) 
				{
					_pcx.load(_url, full);
				}else 
				{
					_pcx.load(_url, full, loadingmc);
				}
				
			}else 
			{
				onCOMPLETE();
			}
		}
		
		private function onCOMPLETE(e:Event = null):void 
		{
			e.currentTarget.removeEventListener(Event.COMPLETE, onCOMPLETE);
			now_load_id++;
			if (now_load_id<num) 
			{
				loadpcx(now_load_id);
			}else 
			{
				dispatchEvent(new Event("COMPLETE"));
			}
		}
		/**
		 * 取得影像
		 * @param	_id 序號
		 * @return
		 */
		public function pcxAutoSize(_id:int):PcxAutoSize
		{
			var _pcx:PcxAutoSize = pcx_arr[_id];
			var _ok:Boolean = _pcx.isload;
			if (!_ok&&_id!=now_load_id)
			{
				stopNowAndLoad(_id);
			}
			return _pcx;
		}
		
		private function stopNowAndLoad(_id:int):void
		{
			var _pcx:PcxAutoSize = pcx_arr[now_load_id];
			_pcx.close();
			_pcx = pcx_arr[_id];
			_pcx.setup(ww, hh);
			_pcx.addEventListener(Event.COMPLETE, onJpCOMPLETE);
			_pcx.load(pcx_url_arr[_id], full, loadingmc);
		}
		
		private function onJpCOMPLETE(e:Event):void 
		{
			e.currentTarget.removeEventListener(Event.COMPLETE, onJpCOMPLETE);
			loadpcx(now_load_id);
		}
	}

}